# -*- coding: utf-8 -*-

"""
Date: 2023/2/24 15:27
Author: Darker
"""
import json
from typing import Dict, Text
from urllib import parse
import random

import requests
from faker import Faker

from utils.cache_utils import cacheUtils


class MyRequests(requests.Request):
    baseUrl = "https://www.tapd.cn"
    fake = Faker()

    @property
    def baseHeader(self):
        return {"User-Agent": self.fake.chrome()}

    @property
    def headerFormEncoded(self):
        data = {"Content-Type": "application/x-www-form-urlencoded"}
        data.update(self.baseHeader)
        return data

    @property
    def headerJson(self):
        data = {"Content-Type": "application/json;charset=UTF-8"}
        data.update(self.baseHeader)
        return data

    def get(self, url: Text, params: Dict = None) -> requests.Response:
        """
        发起get请求
        :param url: 接口地址
        :param params: 请求体内容
        :return: requests.Response
        """
        if not params:
            params = {}
        url = parse.urljoin(base=self.baseUrl, url=url)
        return requests.get(url=url, headers=self.baseHeader, params=params, cookies=cacheUtils.cookies)

    def post(self, url: Text, contentType: Text = "json", data: Dict = None, **kwargs) -> requests.Response:
        """
        发起post请求
        :param url: 接口地址
        :param contentType: 请求体类型: ["json", "formUrlencoded", "form", "file"]
        :param data: 请求体内容
        :return: requests.Response
        """
        if not data:
            data = {}
        match contentType:
            case "json":
                headers = self.headerJson
                data = json.dumps(data)
            case "formUrlencoded" | _:
                headers = self.headerFormEncoded
        for k, v in kwargs.items():
            match k:
                case "headers":
                    headers.update(kwargs.get("headers"))
        url = parse.urljoin(base=self.baseUrl, url=url)
        return requests.post(url=url, headers=headers, data=data, cookies=cacheUtils.cookies)

    def head(self, url: Text, data: Dict = None) -> requests.Response:
        """发起head请求"""
        if not data:
            data = {}
        url = parse.urljoin(base=self.baseUrl, url=url)
        return requests.head(url=url, headers=self.baseHeader, data=data, cookies=cacheUtils.cookies)


myRequest = MyRequests()
if __name__ == '__main__':
    r = myRequest.get("/")
    print(r)
